package com.jrsoft.jrcore.http;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * @author 杨广
 * @time 2019/1/21 15:48
 * @des ${防止接口返回空报错
 * https://stackoverflow.com/questions/35744795/retrofit2-error-java-io-eofexception-end-of-input-at-line-1-column-1}
 */
public class NullOnEmptyConverterFactory extends Converter.Factory {

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        final Converter<ResponseBody, ?> delegate = retrofit.nextResponseBodyConverter(this, type, annotations);
        return (Converter<ResponseBody, Object>) body -> {
            if (body.contentLength() == 0) {
                return null;    //body长度为0,则直接返回null,代表着OkHttpCall中parseResponse(rawResponse)方法已执行结束,接着就调用Callback<T>的onResponse方法
            }
            return delegate.convert(body);  //长度不为0,则调用下一个reponseBodyConverter
        };
    }
}